<template>
  <div>
    <el-card>
      <el-row style="margin-bottom: 10px">
        <el-col span="auto" style="margin-right: 10px">
          <el-input v-model="searchKeyWord" placeholder="输入关键字搜索"></el-input>
        </el-col>
        <el-col :span="2" style="margin-right: 10px">
          <el-select v-model="selectSex" placeholder="性别" value="">
            <el-option label="" value=""></el-option>
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2" style="margin-right: 10px">
          <el-select v-model="selectDisabled" placeholder="是否封禁" value="">
            <el-option label="" value=""></el-option>
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-col>
        <el-col span="auto" style="margin-right: 10px">
          <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-col>
        <el-col span="auto">
          <AddButton></AddButton>
        </el-col>
      </el-row>
      <el-table :data="tableData" border>
        <el-table-column label="ID" prop="id" width="60" header-align="center" align="center" sortable></el-table-column>
        <el-table-column label="头像" prop="imgUrl" width="80" header-align="center" align="center">
          <template slot-scope="scope">
            <el-avatar size='medium' :src="scope.row.imgUrl"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="phone" width="110" header-align="center" align="center">
          <template slot-scope="scope">
            <span v-html="scope.row.phone"></span>
          </template>
        </el-table-column>
        <el-table-column label="QQ邮箱" prop="qqEmail" width="200" header-align="center" align="center">
          <template slot-scope="scope">
            <span v-html="scope.row.qqEmail"></span>
          </template>
        </el-table-column>
        <el-table-column label="昵称" prop="nickname" width="120" header-align="center" align="center">
          <template slot-scope="scope">
            <span v-html="scope.row.nickname"></span>
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="sex" width="60" header-align="center" align="center"></el-table-column>
        <el-table-column label="账号状态" prop="disableStatus" width="120" header-align="center" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.disableStatus === '封禁' ? 'danger' : 'success'" disable-transitions>{{
              scope.row.disableStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色信息" prop="role" width="120" header-align="center" align="center">
          <template slot-scope="scope">
            <el-popover placement="right" width="300" trigger="click">
              <el-tag :key="role.id" v-for="role in dynamicTags" closable size="mini"
                style="margin-right: 10px; margin-bottom: 10px" :disable-transitions="false"
                @close="handleDeleteTag(scope.row.id, role.id)">
                {{ role.roleName }}
              </el-tag>
              <el-dropdown style="margin-right: 10px" @command="handleCommand">
                <el-tag class="el-icon-plus" size="mini"></el-tag>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(role, index) in roleList" :key="index"
                    :command="{ userId: scope.row.id, roleId: role.id }">
                    {{ role.roleName }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button size="mini" type="primary" plain slot="reference"
                @click="getDynamicTags(scope.row.id)">查看</el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="registerTime" width="200" header-align="center" align="center"
          sortable></el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleOpenEdit(scope.row)"
              style="margin-right: 10px">修改</el-button>
            <el-dialog title="修改用户" :visible.sync="dialogue" width="35%">
              <el-form :model="form" ref="form" :rules="rules" label-width="100px">
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="form.nickname" autocomplete="off" style="width: 70%" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="form.password" autocomplete="off" style="width: 70%" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                  <el-input v-model="form.phone" autocomplete="off" style="width: 70%" placeholder="请输入手机"></el-input>
                </el-form-item>
                <el-form-item label="QQ 邮箱" prop="qqEmail">
                  <el-input v-model="form.qqEmail" autocomplete="off" style="width: 70%"
                    placeholder="请输入 QQ 邮箱"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex">
                    <el-radio label="男"></el-radio>
                    <el-radio label="女"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogue = false">取 消</el-button>
                <el-button type="primary" @click="handleEdit(scope.row)">确 定</el-button>
              </span>
            </el-dialog>
            <el-button size="mini" type="danger" @click="handleOpenDisable(scope.row)"
              v-show="scope.row.disableStatus === '封禁' ? false : true">封禁</el-button>
            <el-dialog title="封禁用户" :visible.sync="disableDialog" width="35%">
              <el-form :model="form" ref="form" :rules="rules" label-width="100px">
                <el-form-item label="QQ 邮箱" prop="qqEmail">
                  <el-input v-model="form.qqEmail" autocomplete="off" style="width: 70%" :readonly="true"></el-input>
                </el-form-item>
                <el-form-item label="封禁结束时间" prop="disableTime">
                  <el-radio-group v-model="disableTimeType">
                    <el-radio :label="0">永久封禁</el-radio>
                    <el-radio :label="1">临时封禁</el-radio>
                  </el-radio-group>
                  <el-date-picker v-model="disableTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                    autocomplete="off" style="width: 70%" placeholder="请选择封禁时间"
                    v-show="disableTimeType ? true : false"></el-date-picker>
                </el-form-item>
                <el-form-item label="封禁原因" prop="disableReason">
                  <el-input type="textarea" v-model="disableReason" autocomplete="off" style="width: 70%"
                    placeholder="请输入封禁原因"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="disableDialog = false">取 消</el-button>
                <el-button type="primary" @click="editUserDisable(scope.row)">确 定</el-button>
              </span>
            </el-dialog>
            <el-button size="mini" type="success" @click="handleOpenUntieDisable(scope.row)"
              v-show="scope.row.disableStatus === '封禁' ? true : false">解禁</el-button>
            <el-dialog title="解禁用户" :visible.sync="untiedisableDialog" width="35%">
              <el-form :model="form" ref="form" :rules="rules" label-width="100px">
                <el-form-item label="QQ 邮箱" prop="qqEmail">
                  <el-input v-model="form.qqEmail" autocomplete="off" style="width: 70%" :readonly="true"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="untiedisableDialog = false">取 消</el-button>
                <el-button type="primary" @click="userUntieDisable(scope.row)">确 定</el-button>
              </span>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页 -->
      <div style="text-align: center">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="currentPage" :page-sizes="[10, 15, 20]" :page-size="pageSize" :total="totalSize" background
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getDetailInfoById, editUserWithAdmin, userDisable, useruntieDisable } from '@/api/auth/user'
import { formatRoleTags, formatUserPaginationData } from '@/utils/format'
import AddButton from '@/views/user/user/components/AddButton.vue'
import { validPhone, validEmail, validPassword } from '@/utils/validate'
import { getAllRole } from '@/api/auth/role'
import { addUserRole, deleteUserRole } from '@/api/auth/user-role'
import { searchByMultipleCondition } from '@/api/search/user'

export default {
  components: { AddButton },
  provide() {
    return {
      getDataList: this.getDataList,
    }
  },
  data() {
    const validateNickname = (rule, value, callback) => {
      if (value.length > 15) {
        callback(new Error('昵称长度不能大于15位'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!validPhone(value) && value !== '') {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value) && value !== '' && value !== undefined) {
        callback(new Error('密码限制为6~18个字符，至少包含1个字母、1个数字、1个特殊字符'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value) && value !== '') {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    return {
      dataList: [],
      tableData: [],
      searchKeyWord: '',
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      dynamicTags: [],
      dialogue: false,
      disableDialog: false,
      disableTime: new Date(),
      disableReason: '',
      untiedisableDialog: false,
      disableTimeType: 0,
      form: {
        id: '',
        imgUrl: '',
        nickname: undefined,
        password: undefined,
        phone: '',
        qqEmail: '',
        sex: '',
      },
      rules: {
        nickname: [{ required: false, trigger: 'blur', validator: validateNickname }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        password: [{ required: false, trigger: 'blur', validator: validatePassword }],
        qqEmail: [{ required: false, trigger: 'blur', validator: validateEmail }]
      },
      roleList: [],
      selectSex: '',
      selectDisabled: ''
    }
  },
  methods: {
    init(data) {
      this.form = {
        id: data.id,
        imgUrl: data.imgUrl,
        nickname: data.nickname,
        password: data.password,
        phone: data.phone,
        qqEmail: data.qqEmail,
        sex: data.sex
      }
    },
    handleOpenEdit(row) {
      this.dialogue = true
      this.init(row)
    },
    handleOpenDisable(row) {
      this.disableDialog = true
      this.init(row)
    },
    handleOpenUntieDisable(row) {
      this.untiedisableDialog = true
      this.init(row)
    },
    handleEdit(row) {
      this.$refs.form.validate(valid => {
        if (valid) {
          editUserWithAdmin({
            "id": this.form.id,
            "imgUrl": this.form.imgUrl,
            "nickname": this.form.nickname ? this.form.nickname : null,
            "password": this.form.password ? this.form.password : null,
            "phone": this.form.phone ? this.form.phone : null,
            "qqEmail": this.form.qqEmail ? this.form.qqEmail : null,
            "sex": this.form.sex === '男' ? 1 : 0
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success({
                message: res.data.message,
                duration: 1000
              })
              this.getDataList()
              this.dialogue = false
            } else {
              // this.$message.error({
              //   message: res.data.message,
              //   duration: 1000
              // })
            }
          })
        } else {
          return false
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getDataList()
    },
    handleDeleteTag(userId, roleId) {
      deleteUserRole({
        userId: Number(userId),
        roleId: Number(roleId)
      }).then(res => {
        if (res.data.code === 200) {
          this.getDynamicTags(userId)
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    },
    getDynamicTags(val) {
      getDetailInfoById({ 'id': val }).then(res => {
        if (res.data.code === 200) {
          this.dynamicTags = formatRoleTags(res.data.userDetailInfoVO.roleList)
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    },
    handleCommand(command) {
      const { userId, roleId } = command
      addUserRole({
        "roleId": Number(roleId),
        "userId": Number(userId)
      }).then(res => {
        if (res.data.code === 200) {
          this.getDynamicTags(userId)
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    },
    getAllRole() {
      getAllRole({ "pageNo": 1, "pageSize": 100 }).then(res => {
        if (res.data.code === 200) {
          this.roleList = res.data.pageResult.dataList
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    },
    getDataList() {
      searchByMultipleCondition({
        disableStatus: this.selectDisabled === '' ? undefined : Number(this.selectDisabled),
        keyword: this.searchKeyWord === '' ? undefined : this.searchKeyWord,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sex: this.selectSex === '' ? undefined : Number(this.selectSex)
      }).then(res => {
        if (res.data.code === 200) {
          this.dataList = res.data.searchResult.dataList
          this.tableData = formatUserPaginationData(this.dataList)
          this.totalSize = res.data.searchResult.totalCount
          this.getAllRole()
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    },
    search() {
      searchByMultipleCondition({
        disableStatus: this.selectDisabled === '' ? undefined : Number(this.selectDisabled),
        keyword: this.searchKeyWord === '' ? undefined : this.searchKeyWord,
        pageNo: 1,
        pageSize: this.pageSize,
        sex: this.selectSex === '' ? undefined : Number(this.selectSex)
      }).then(res => {
        if (res.data.code === 200) {
          this.tableData = formatUserPaginationData(res.data.searchResult.dataList)
          this.totalSize = res.data.searchResult.totalCount
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    },
    editUserDisable(row) {
      console.log(Date.parse(this.disableTime))
      userDisable({
        "userId": this.form.id,
        "reason": this.disableReason,
        "time": this.disableTimeType ? Date.parse(this.disableTime) : -1,
        "qqEmail": this.form.qqEmail
      }).then(res => {
        if (res.data.code === 200) {
          this.disableDialog = false,
            this.$message.success({
              message: res.data.message,
              duration: 1000
            })
          this.getDataList()
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    },
    userUntieDisable(row) {
      console.log(Date.parse(this.untiedisableTime))
      useruntieDisable({
        "userId": this.form.id,
        "qqEmail": this.form.qqEmail,
      }).then(res => {
        if (res.data.code === 200) {
          this.untiedisableDialog = false,
            this.$message.success({
              message: res.data.message,
              duration: 1000
            })
          this.getDataList()
        } else {
          // this.$message.error({
          //   message: res.data.message,
          //   duration: 1000
          // })
        }
      })
    }
  },
  created() {
    this.getDataList()
  }
}
</script>

<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
}
</style>
